package com.example.user.myfirstapp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.example.user.myfirstapp.MyApplication;
import com.example.user.myfirstapp.R;
import com.example.user.myfirstapp.common.Constant;
import com.example.user.myfirstapp.common.ImageHelper;
import com.example.user.myfirstapp.common.LoadingDialog;
import com.example.user.myfirstapp.entity.Goods;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SearchListActivity extends Activity implements View.OnClickListener{
    private TextView tv_searchlist_orderbytime,tv_searchlist_orderbypopularity,tv_searchlist_orderbygrice;
    private ImageView iv_searchlist_orderbygrice;
    private LinearLayout ll_searchlist_orderbygrice;
    private Intent intent;
    private String search_key;
    private Button bt_searchlist_return;
    private EditText et_searchlist_search;
    private PullToRefreshListView mPullRefreshListView;
    private NetworkImageViewAdapter adapter;
    private ArrayList<Goods> goodsList;
    private String url="http://"+ Constant.host+":"+Constant.port+"/api/Goods/GetSearchSpiltPageList";
    private boolean isdsec=false;
    private int listSort=1;//1、时间降序  2、人气降序  3、价格降序  4、价格升序
    private int pageIndex,pageSize;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchlist);

        bt_searchlist_return=(Button)findViewById(R.id.bt_searchlist_return);
        bt_searchlist_return.setOnClickListener(this);
        et_searchlist_search=(EditText)findViewById(R.id.et_searchlist_search);
        et_searchlist_search.setOnClickListener(this);

        tv_searchlist_orderbytime=(TextView)findViewById(R.id.tv_searchlist_orderbytime);
        tv_searchlist_orderbytime.setBackgroundResource(R.drawable.rounded_left_red);//红色左边圆角背景
        tv_searchlist_orderbytime.setTextColor(getResources().getColor(R.color.colorTextWhite));//白色字体
        tv_searchlist_orderbytime.setOnClickListener(this);
        tv_searchlist_orderbypopularity=(TextView)findViewById(R.id.tv_searchlist_orderbypopularity);
        tv_searchlist_orderbypopularity.setOnClickListener(this);
        ll_searchlist_orderbygrice=(LinearLayout)findViewById(R.id.ll_searchlist_orderbygrice);
        ll_searchlist_orderbygrice.setOnClickListener(this);
        tv_searchlist_orderbygrice=(TextView)findViewById(R.id.tv_searchlist_orderbygrice);
        iv_searchlist_orderbygrice=(ImageView)findViewById(R.id.iv_searchlist_orderbygrice);

        //获取传过来的参数
        intent =getIntent();
        search_key = intent.getStringExtra("serachKey");
        et_searchlist_search.setText(search_key);

        //PullToRefreshListView
        initPullToRefreshListView();
    }

    public void onClick(View v) {
        String url;
        switch (v.getId()) {
            case R.id.et_searchlist_search:
                intent =new Intent(this, SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.bt_searchlist_return:
                this.finish();
                //从左往右切换
                this.overridePendingTransition(0,R.animator.slide_right_out);
                break;
            case R.id.tv_searchlist_orderbytime:
                tv_searchlist_orderbypopularity.setBackgroundResource(R.drawable.border_leftright_red);
                tv_searchlist_orderbypopularity.setTextColor(getResources().getColor(R.color.colorRed));//红色字体
                ll_searchlist_orderbygrice.setBackgroundResource(0);//去除背景
                tv_searchlist_orderbygrice.setTextColor(getResources().getColor(R.color.colorRed));//红色字体
                tv_searchlist_orderbytime.setBackgroundResource(R.drawable.rounded_left_red);//红色左边圆角背景
                tv_searchlist_orderbytime.setTextColor(getResources().getColor(R.color.colorTextWhite));//白色字体
                if(isdsec){
                    iv_searchlist_orderbygrice.setBackgroundResource(R.mipmap.ps3);
                }
                else {
                    iv_searchlist_orderbygrice.setBackgroundResource(R.mipmap.ps4);
                }
                //按时间排序，第一页
                listSort=1;
                adapter.remove();//清空之前的数据
                LoadData(listSort,1,Constant.pageSize);

                break;
            case R.id.tv_searchlist_orderbypopularity:
                tv_searchlist_orderbytime.setBackgroundResource(0);//去除背景
                tv_searchlist_orderbytime.setTextColor(getResources().getColor(R.color.colorRed));//红色字体
                ll_searchlist_orderbygrice.setBackgroundResource(0);//去除背景
                tv_searchlist_orderbygrice.setTextColor(getResources().getColor(R.color.colorRed));//红色字体
                tv_searchlist_orderbypopularity.setBackgroundColor(getResources().getColor(R.color.colorRed));//红色左边圆角背景
                tv_searchlist_orderbypopularity.setTextColor(getResources().getColor(R.color.colorTextWhite));//白色字体
                if(isdsec){
                    iv_searchlist_orderbygrice.setBackgroundResource(R.mipmap.ps3);
                }
                else {
                    iv_searchlist_orderbygrice.setBackgroundResource(R.mipmap.ps4);
                }
                //按人气排序，第一页
                listSort=2;
                adapter.remove();//清空之前的数据
                LoadData(listSort,1,Constant.pageSize);

                break;
            case R.id.ll_searchlist_orderbygrice:
                tv_searchlist_orderbytime.setBackgroundResource(0);//去除背景
                tv_searchlist_orderbytime.setTextColor(getResources().getColor(R.color.colorRed));//红色字体
                tv_searchlist_orderbypopularity.setBackgroundResource(R.drawable.border_leftright_red);
                tv_searchlist_orderbypopularity.setTextColor(getResources().getColor(R.color.colorRed));//红色字体
                ll_searchlist_orderbygrice.setBackgroundResource(R.drawable.rounded_right_red);//红色右圆角背景
                tv_searchlist_orderbygrice.setTextColor(getResources().getColor(R.color.colorTextWhite));//白色字体
                isdsec=!isdsec;
                if(isdsec){
                    iv_searchlist_orderbygrice.setBackgroundResource(R.mipmap.ps2);
                    listSort=3;
                }
                else {
                    iv_searchlist_orderbygrice.setBackgroundResource(R.mipmap.ps1);
                    listSort=4;
                }
                //按价格排序，第一页
                adapter.remove();//清空之前的数据
                LoadData(listSort,1,Constant.pageSize);
                break;
            default:
                break;
        }
    }

    private void initPullToRefreshListView(){
        mPullRefreshListView=(PullToRefreshListView)findViewById(R.id.search_refresh_listlview);
        ILoadingLayout startLabels = mPullRefreshListView.getLoadingLayoutProxy(true,false);
        ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(false,true);
        startLabels.setPullLabel(getString(R.string.startPullLabel));
        startLabels.setRefreshingLabel(getString(R.string.refreshingLabel));
        startLabels.setReleaseLabel(getString(R.string.releaseLabel));
        endLabels.setPullLabel(getString(R.string.endPullLabel));
        endLabels.setRefreshingLabel(getString(R.string.refreshingLabel));
        endLabels.setReleaseLabel(getString(R.string.releaseLabel));
        goodsList = new ArrayList<Goods>();
        adapter = new NetworkImageViewAdapter(this,goodsList);
        mPullRefreshListView.setAdapter(adapter);
        //默认读取第1页10条数据
        LoadData(listSort,1,Constant.pageSize);
        //点击事件
        mPullRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView lv = (ListView)parent;
                Object object=lv.getItemAtPosition(position);
                Goods goods=(Goods)object;
                intent=new Intent(SearchListActivity.this,GoodsInfoActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("goods", goods);
                intent.putExtras(bundle);
                startActivity(intent);
                //从右往左切换
                overridePendingTransition(R.animator.slide_right_in,0);

            }
        });
        //刷新
        mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            //下拉刷新
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //执行刷新函数
                adapter.remove();//清空之前的数据(这里偷懒了)
                LoadData(listSort,1,Constant.pageSize);
            }

            //上拉加载
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                int count = adapter.getCount();
                int iszero=count%Constant.pageSize;
                int currentPageIndex=iszero==0?(count/Constant.pageSize):(count/Constant.pageSize+1);
                int nextPageIndex=currentPageIndex+1;
                LoadData(listSort,nextPageIndex,Constant.pageSize);
            }
        });
    }
    private void LoadData(int sort,int index,int size){
        LoadingDialog.showLoading(this,"请稍后...");
        listSort=sort;
        pageIndex=index;
        pageSize=size;
        final StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        showData(result);
                        //下拉刷新或上拉加载后执行
                        mPullRefreshListView.onRefreshComplete();
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(SearchListActivity.this, "网络请求失败",
                                Toast.LENGTH_LONG).show();
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                }
        ){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String,String> params = new HashMap<>() ;
                    params.put("searchKey",search_key);
                    params.put("searchSort",String.valueOf(listSort));
                    params.put("pageIndex",String.valueOf(pageIndex));
                    params.put("pageSize",String.valueOf(pageSize));
                    return params ;
                }
        };
        request.setTag("getSearchGoodsListData");
        MyApplication.getHttpQueue().add(request);
    }
    private void showData(String json){
        try {
            //因为下面可能会关闭上拉加载功能，所以执行此方法前开启
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
            Gson gson = new Gson();
            ArrayList<Goods> tempList = gson.fromJson(json, new TypeToken<ArrayList<Goods>>() {}.getType());
            if(tempList!=null&&tempList.size()>0) {
                adapter.addItem(tempList);
                adapter.notifyDataSetChanged();
            }
            else {
                if(adapter.getCount()>0){
                    Toast.makeText(this, "没有更多数据了",
                            Toast.LENGTH_SHORT).show();
                    mPullRefreshListView.onRefreshComplete();
                    //没有更多数据了，关闭上拉加载功能
                    mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                }
                //adapter.getCount()=0表示是第一次（第一页）没有数据，所以这里显示暂无数据
                else {
                    Toast.makeText(this, "暂无数据",
                            Toast.LENGTH_SHORT).show();
                    //暂无数据，关闭上拉下拉功能
                    mPullRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
                }
            }
        }
        catch (Exception e){
        }
    }
    private class NetworkImageViewAdapter extends BaseAdapter {
        private LayoutInflater layoutInflater = null;
        private ArrayList<Goods> goodslist=null;
        class ViewHolder {
            TextView title;
            TextView price;
            TextView marketprice;
            NetworkImageView image;
        }
        public NetworkImageViewAdapter(Context context, ArrayList<Goods> list)
        {
            layoutInflater = LayoutInflater.from(context);
            goodslist=list;
        }
        @Override
        public int getCount() {
            return goodslist == null ? 0 : goodslist.size();
        }

        @Override
        public Object getItem(int position) {
            return goodslist == null ? null : goodslist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void addItem(ArrayList<Goods> nlist){
            goodslist.addAll(nlist);
        }

        public void remove(){
            goodslist.clear();
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            String baseUrl="http://"+ Constant.host+":"+Constant.port;
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = layoutInflater.inflate(R.layout.goodslist_item, null);
                viewHolder.title = (TextView) convertView.findViewById(R.id.tv_goodsitem_name);
                viewHolder.price = (TextView) convertView.findViewById(R.id.tv_goodsitem_price);
                viewHolder.price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//字体中间加横线
                viewHolder.marketprice=(TextView)convertView.findViewById(R.id.tv_goodsitem_marketprice);
                viewHolder.image = (NetworkImageView) convertView.findViewById(R.id.niv_goodsitem_img);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            Goods goods = goodslist.get(position);
            viewHolder.title.setText(goods.getGoodsName());
            viewHolder.price.setText("￥"+String.valueOf(goods.getGoodsPrice()));
            viewHolder.marketprice.setText("￥"+String.valueOf(goods.getGoodsMarketPrice()));
            ImageHelper.showImageByNetworkImageView(MyApplication.getHttpQueue(), viewHolder.image, baseUrl+goods.getGoodsDisplayImgUrl());
            return convertView;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束时队列里面注销
        MyApplication.getHttpQueue().cancelAll("getSearchGoodsListData");
    }
}
